package spring.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import spring.services.SpittleRepo;
import spring.Spittle;

import java.util.List;
import java.util.Map;

/**
 * Created by kassadin@foxmail.com on 2017/4/26 0026.
 */
@Controller
@RequestMapping("/spittles")
public class SpittleController {

    // http://stackoverflow.com/questions/40678981/how-to-retrive-string-value-of-long-max-value-in-compile-time-in-java#
    private SpittleRepo spittleRepo;

    @Autowired
    public SpittleController(SpittleRepo spittleRepo) {
        this.spittleRepo = spittleRepo;
    }

    @RequestMapping
    public List<Spittle> spittles(
            @RequestParam(value = "max", defaultValue = Long.MAX_VALUE + "") long max,
            @RequestParam(value = "count", defaultValue = "20") int count) {

//        model.addAttribute(spittes); //  List<Spittle>  key 为 spittleList
        // 也可以用map 替代 Model
//        model.addAttribute("spittleList", spittes);
        List<Spittle> spittles = spittleRepo.findSpittes(max, count);
        return spittles;
    }

    @RequestMapping(value = "/{spittleId}", method = RequestMethod.GET)
    public String showSpittle(
            @PathVariable("spittleId") long spittleId,
            Map model) {
        model.put("spittle", spittleRepo.findOne(spittleId));
        return "spittle";
    }
}
